import { DirectiveBinding } from 'vue';
import { InputTarget } from '@/interface/utils/directive';

export default (app: any) => {
  /**
   * 自动去空格
   * v-input-trim="{set(val){key = val}}"
   */
  app.directive('input-trim', {
    mounted(el: Element, binding: DirectiveBinding<any>): void {
      let inputDom: HTMLInputElement | HTMLTextAreaElement =
        el.getElementsByTagName('input')[0];
      if (!inputDom) {
        inputDom = el.getElementsByTagName('textarea')[0];
      }
      if (!inputDom) return;
      inputDom.addEventListener('blur', function (event: InputTarget) {
        const value = event.target.value;
        const value_trim: string = value.trim();
        binding.value.set(value_trim);
      });
    },
  });

  /**
   * v-input-fixed="{set(val){key = val}}"
   */
  app.directive('input-fixed', {
    mounted(el: Element, binding: DirectiveBinding<any>): void {
      //intege 整数位数  decimal小数位数 abs是否取绝对值
      const { intege = 4, decimal = 1, abs = true, max, min } = binding.value;

      let inputDom: HTMLInputElement | HTMLTextAreaElement =
        el.getElementsByTagName('input')[0];
      if (!inputDom) {
        inputDom = el.getElementsByTagName('textarea')[0];
      }
      if (!inputDom) return;

      //增加失去焦事件
      inputDom.addEventListener('blur', function (event: InputTarget) {
        const value = event.target.value.replace(/[^-\d.]/g, '');

        const list: Array<string | number> = value.split('.');

        const valueIntege: string = list[0].toString();

        const integeNumber =
          valueIntege.length > intege
            ? valueIntege.slice(0, +valueIntege > 0 ? intege : intege + 1)
            : valueIntege;

        let returnNumb: number = +integeNumber;

        if (decimal && value.indexOf('.') > -1) {
          //去除整数位
          list.shift();
          const decimalNumber = list.join('').slice(0, decimal);
          returnNumb = +`${integeNumber}.${decimalNumber || 0}`;
        }
        if (abs) returnNumb = Math.abs(+returnNumb);
        if (max && max < returnNumb) returnNumb = max;
        if (min && min > returnNumb) returnNumb = min;
        binding.value.set(returnNumb || 0);
      });
    },
  });
};
